import { access, origin } from "@/config/config";
import { usePageEvent } from "@remax/framework-shared";
import { ActionSheet, Button, Cell, Col, Icon, Row } from "annar";
import React, { useEffect, useState } from "react";
import { useNativeEffect } from "remax";
import {
  closeBLEConnection,
  getStorageSync,
  Swiper,
  SwiperItem,
  Video,
  View,
} from "remax/wechat";
import CommentButton from "../comment-button";
import FollowButton from "../follow-button";
import LikeButton from "../like-button";
import styles from "./index.css";

let windowWidth = wx.getSystemInfoSync().windowWidth;
let windowHeight = wx.getSystemInfoSync().windowHeight;
//rpx与px单位之间的换算 : 750/windowWidth = 屏幕的高度（rpx）/windowHeight
let maxHeight = (750 * windowHeight) / windowWidth;

let data: any = {
  curQueue: [], // 当前播放列表, 理论上只有 3 个
  prevQueue: [], // 已播放列表
  nextQueue: [], // 待播放列表
  circular: false,
  _last: 1, // 上一次显示
  _change: -1,
  _invalidDown: 0,
  _invalidUp: 0,
};

const getRandomColor = () => {
  const rgb = [];
  for (let i = 0; i < 3; i++) {
    let color = Math.floor(Math.random() * 256).toString(16);
    color = color.length === 1 ? "0" + color : color;
    rgb.push(color);
  }
  return "#" + rgb.join("");
};

export type videoSwpierItem = {
  id: string; // 视频的id
  videoDesc: string; // 视频描述
  likeCounts: number; // 点赞数
  authorId: string; // 作者id
  nickName: string; // 上传用户昵称
  userAvatar: string; // 上传用户的头像图片路径
  coverPath: string; // 视频的封面图路径
  videoPath: string; // 视频的路径
  isFollow: boolean; // 该用户是否关注了该视频的作者
  isLike: boolean; // 是否喜欢该视频
  commentNumber: number; // 弹幕数量
  danmuList: danmu[]; // 弹幕列表
};

type danmu = {
  nickName: string;
  userAvatar: string;
  text: string;
  color: string;
  time: number;
  createTime: string;
};

type Props = {
  videoList: videoSwpierItem[];
};

export default (props: Props) => {
  const [videoList, setVideoList] = useState<videoSwpierItem[]>(
    props.videoList
  );
  const [loop, setLoop] = useState(true);
  const [circular, setCircular] = useState(data.circular);
  const [curQueue, setCurQueue] = useState(props.videoList.slice(0, 3));
  const [nextQueue, setNextQueue] = useState(props.videoList.slice(3));
  let oldVideoList = videoList.splice(0);
  const [open, setOpen] = React.useState(false);
  const [actions, setAction] = useState([]);
  const [inputValue, setInputValue] = React.useState<string>("");
  const [currentTime, setCurrentTume] = React.useState<number>(0);
  let inputValue1 = "";

  let _videoContexts: WechatMiniprogram.VideoContext[];

  // // TODO: 参入参数改变, 相应状态发生改变
  // useEffect(() => {
  //   // 比较差异, 计算新插入到值
  //   if (oldVideoList.length + 1 === videoList.length) {
  //     // 插入一行
  //     _videoListChanged(videoList.splice(videoList.length - 1));
  //   }
  //   oldVideoList = videoList.slice(0);
  // }, [props.videoList]);

  // useNativeEffect(() => {
  //   // 比较差异, 计算新插入到值
  //   if (oldVideoList.length + 1 === videoList.length) {
  //     // 插入一行
  //     _videoListChanged(videoList.splice(videoList.length - 1));
  //   }
  //   oldVideoList = videoList.slice(0);
  // }, [props.videoList]);

  useEffect(() => {
    console.log(props.videoList);
    setVideoList([...props.videoList]);
    setCurQueue(props.videoList.slice(0, 3));
    setNextQueue(props.videoList.slice(3));
    data.curQueue = props.videoList.slice(0, 3);
    data.nextQueue = props.videoList.slice(3);
  }, [props.videoList]);

  useNativeEffect(() => {
    console.log("effect", videoList);
  }, [props.videoList]);

  console.log("video", videoList);
  usePageEvent("onLoad", () => {
    _videoContexts = [
      wx.createVideoContext("video_0"),
      wx.createVideoContext("video_1"),
      wx.createVideoContext("video_2"),
    ];
    data._videoContexts = _videoContexts;
    data.curQueue = curQueue;
    data.nextQueue = nextQueue;
    console.log(nextQueue);
    console.log(curQueue);
  });

  const _videoListChanged = (newVal: any) => {
    newVal.forEach((item: any) => {
      data.nextQueue.push(item);
    });

    if (data.curQueue.length === 0) {
      setCurQueue(data.nextQueue.splice(0, 3));
      playCurrent(1);
    }
  };

  // 避免卡顿
  const playCurrent = (current: number) => {
    data._videoContexts.forEach(
      (ctx: WechatMiniprogram.VideoContext, index: number) => {
        index !== current ? ctx.pause() : ctx.play();
      }
    );
    // setTimeout(() => ctx.play(), 100)
  };

  const animationFinish = (event: { detail: { current: any } }) => {
    const { _last, _change, curQueue, prevQueue, nextQueue } = data;
    console.log(data);

    let current = event.detail.current; // current 滑动结束后当前的 item_id

    console.log(current);

    let diff = current - _last;

    data._last = current;
    playCurrent(current);
    console.log("change", curQueue[current].id);
    if (prevQueue.length === 0 && current === 0) {
      console.log("刷新页面");
      // let loginInfo = getStorageSync("loginInfo");

      // wx.request({
      //   url: `${origin}/video/initVideoSwiper/-1`,
      //   header: {
      //     token: loginInfo.token,
      //     "Content-Type": "application/x-www-form-urlencoded",
      //     Accept: "application/json",
      //   },
      //   success: (res: any) => {
      //     let videoList1 = res.data.data;
      //     console.log("res", videoList1);
      //     data.prevQueue = [];
      //     data.curQueue = videoList1.slice(0, 3);
      //     data.nextQueue = videoList1.slice(3);
      //     console.log(data.curQueue);
      //     setCurQueue((old: any) => data.curQueue);
      //   },
      // });
    } else {
      // 添加新的视频
      let loginInfo = getStorageSync("loginInfo");
      wx.request({
        url: `${origin}/video/random`,
        header: {
          token: loginInfo.token,
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
        },
        success: (res: any) => {
          console.log(res);
          let video = res.data.data;
          data.nextQueue.push(video);
        },
      });
    }

    if (diff === 0) return;

    const direction = diff === 1 || diff === -2 ? "up" : "down"; // 手指滑动方向

    if (direction === "up") {
      if (data._invalidDown == 0) {
        const change = (_change + 1) % 3;
        const add = nextQueue.shift();
        const remove = curQueue[change];

        if (add) {
          prevQueue.push(remove);
          curQueue[change] = add;
          data._change = change;
        } else {
          data._invalidUp += 1;
        }
      } else {
        data._invalidDown -= 1;
      }
    }

    if (direction == "down") {
      if (data._invalidUp == 0) {
        const change = _change;
        const remove = curQueue[change];
        const add = prevQueue.pop();

        if (add) {
          curQueue[change] = add;
          nextQueue.unshift(remove);
          data._change = (change - 1 + 3) % 3;
        } else {
          data._invalidDown += 1;
        }
      } else {
        data._invalidUp -= 1;
      }
    }

    let circular = true;
    console.log(prevQueue, curQueue, nextQueue);

    if (nextQueue.length === 0 && current !== 0) {
      circular = false;
    }

    if (prevQueue.length === 0 && current !== 2) {
      circular = false;
    }

    console.log(data.prevQueue, data.curQueue, data.nextQueue);
    setCurQueue(curQueue);
    setCircular(circular);
  };

  const bindChange = (v: any) => {
    // inputValue1 = v.target.value;
    setInputValue(v.target.value);
  };

  const timeUpdate = (e: any) => {
    setCurrentTume(parseInt(e.detail.currentTime));
  };

  return (
    <View style={{ height: maxHeight }}>
      <Swiper
        className={styles.video_swiper}
        circular={circular}
        easing-function="default"
        vertical
        current={1}
        duration={1000}
        onAnimationFinish={animationFinish}
      >
        {curQueue.map((item: any, index: number) => (
          <SwiperItem key={item.id}>
            <View
              style={{
                display: "flex",
                flexDirection: "column",
                height: "inherit",
              }}
            >
              <Video
                poster={item.coverPath}
                id={`video_${index}`}
                className={styles.video_item}
                enableDanmu={true}
                danmuBtn={true}
                danmuList={item.danmuList.map((item1: any) =>
                  Object.assign(
                    {},
                    { text: item1.text, color: item1.color, time: item1.time }
                  )
                )}
                objectFit="cover"
                loop={loop}
                src={`${access}${item.videoPath}`}
                showProgress={true}
                showFullscreenBtn={false}
                showPlayBtn={true}
                showCenterPlayBtn={true}
                enableProgressGesture={true}
                enablePlayGesture={true}
                playBtnPosition="center"
                onTimeUpdate={timeUpdate}
              />
              <View
                style={{ position: "absolute", bottom: "200px", left: "50px" }}
              >
                <View style={{ color: "#fff" }}>@{item.nickName}</View>

                <View style={{ color: "#fff", margin: "10px 0px" }}>
                  {item.videoDesc}
                </View>
              </View>
              <View
                style={{ position: "absolute", right: "20px", top: "400px" }}
              >
                <View
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                  }}
                >
                  <img
                    style={{ margin: "20px auto" }}
                    className={styles.avatar}
                    alt=""
                    width="30px"
                    src={`${access}${item.userAvatar}`}
                  />
                  <FollowButton
                    style={{ margin: "10px 10px 0px 20px" }}
                    authorId={item.authorId}
                    isFollow={item.isFollow}
                  />
                  <LikeButton
                    videoId={item.id}
                    isLike={item.isLike}
                    likeNumber={item.likeCounts}
                  />
                  <CommentButton
                    commentNumber={item.commentNumber}
                    onTap={() => {
                      // 显示弹幕列表
                      setOpen(true);
                      setAction(
                        item.danmuList
                          .map((item1: any, index1: number) =>
                            Object.assign(
                              {},
                              { value: index1, text: item1.text }
                            )
                          )
                          .slice(0)
                      );
                    }}
                  />
                </View>
              </View>
              <View style={{ position: "absolute", bottom: "10px" }}>作者</View>
              <View
                style={{
                  height: "80px",
                  display: "flex",
                  flexDirection: "row",
                }}
              >
                <Cell.Input
                  style={{
                    // position: "absolute",
                    // bottom: "0px",
                    height: "inherit",
                  }}
                  icon="people"
                  label="弹幕内容"
                  placeholder="发送弹幕"
                  border={false}
                  value={inputValue}
                  onChange={bindChange}
                />
                <Button
                  style={{
                    // position: "absolute",
                    // right: "0px",
                    // bottom: "0px",
                    height: "inherit",
                  }}
                  shape="square"
                  look="orange"
                  onTap={() => {
                    console.log(inputValue);
                    if (inputValue === "") return;
                    let danmu = {
                      color: getRandomColor(),
                      text: inputValue,
                    };
                    console.log(danmu);
                    data._videoContexts[index].sendDanmu(danmu);
                    setInputValue("");

                    let item1 = {
                      text: danmu.text,
                      color: danmu.color,
                      time: currentTime,
                    };
                    setCurQueue((old: any[]) => {
                      old[index].commentNumber = item.commentNumber + 1;
                      old[index].danmuList.push(item1);
                      return [...old];
                    });

                    let loginInfo = getStorageSync("loginInfo");
                    wx.request({
                      url: `${origin}/danmu/add`,
                      header: {
                        token: loginInfo.token,
                        "Content-Type": "application/x-www-form-urlencoded",
                        Accept: "application/json",
                      },
                      method: "GET",
                      data: {
                        text: item1.text,
                        color: item1.color,
                        time: item1.time,
                        videoId: item.id,
                      },
                      success: (res: any) => {
                        console.log(res);
                        if (res.data.code === 200) {
                        } else {
                        }
                      },
                    });
                    console.log(inputValue);
                    console.log(videoList);
                  }}
                >
                  发送弹幕
                </Button>
              </View>
            </View>
          </SwiperItem>
        ))}
      </Swiper>

      <ActionSheet
        open={open}
        actions={actions}
        title="弹幕列表"
        cover={true}
        cancelText="收起"
        onCancel={() => setOpen(false)}
        onChange={(a: any, g: any, e: any) => {
          console.log(a, g, e);
          setOpen(false);
        }}
      />
    </View>
  );
};
